package org.hs.phd.odi.tracking.layers;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Polygon;
import java.awt.event.MouseEvent;

import org.hs.phd.common.simpleplayer.PlayerViewerLayer;
import org.hs.phd.common.simpleplayer.frameviewer.FrameViewer;
import org.hs.phd.odi.tracking.filters.TrackSelectionEvent;

public class PolygonAnnotationLayer implements PlayerViewerLayer {

	private FrameViewer viewer;
	private boolean isEnabled;

	private Polygon polygon;
	private Point mousePoint;

	public PolygonAnnotationLayer() {
		this.isEnabled = true;
		reset();
	}

	@Override
	public void mouseClicked(MouseEvent e) {
		// do nothing
	}

	@Override
	public void mouseEntered(MouseEvent e) {
		// do nothing

	}

	@Override
	public void mouseExited(MouseEvent e) {
		// do nothing
	}

	@Override
	public void mousePressed(MouseEvent e) {
		if (polygon == null) {
			polygon = new Polygon();
		}

		if (e.getButton() == MouseEvent.BUTTON1) {

			polygon.addPoint(e.getX(), e.getY());

			if (e.getClickCount() == 2) {
				Polygon modelPolygon = viewer.getTransformation().viewToModel(polygon);

				viewer.getViewerController().fireEvent(new TrackSelectionEvent(modelPolygon));

				reset();
				viewer.repaint();
			}
		} else {
			reset();
			viewer.repaint();
		}
	}

	@Override
	public void mouseReleased(MouseEvent e) {
	}

	private void reset() {
		polygon = null;
	}

	@Override
	public void mouseDragged(MouseEvent e) {
		mousePoint = e.getPoint();
		viewer.repaint();
	}

	@Override
	public void mouseMoved(MouseEvent e) {
		mousePoint = e.getPoint();
		viewer.repaint();
	}

	@Override
	public void setViewer(FrameViewer viewer) {
		this.viewer = viewer;
	}

	@Override
	public void paint(Graphics g) {
		if (polygon != null) {

			Graphics2D g2 = (Graphics2D) g;
			g2.setColor(Color.MAGENTA);
			g2.setStroke(new BasicStroke(2));
			Polygon displayPolygon = getDisplayPolygon();
			g2.drawPolygon(displayPolygon);
			
		}
	}

	private Polygon getDisplayPolygon() {
		Polygon displayPolygon = new Polygon(polygon.xpoints, polygon.ypoints, polygon.npoints);
		displayPolygon.addPoint(mousePoint.x, mousePoint.y);
		return displayPolygon;
	}

	@Override
	public void setEnabled(boolean isEnabled) {
		this.isEnabled = isEnabled;
	}

	@Override
	public boolean isEnabled() {
		return isEnabled;
	}

}
